// pages/addComment/addComment.js
var globalData = getApp().globalData;
var common = require("../../utils/Conmon.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    star: 5,
    OrderId: '',
    GetOrderDetails: [],
    ProductCommentList: [],
    shopID: 0
  },

  /**
   * 填写评价内容
   */
  onInputCommentContent: function(e) {
    var goodsid = e.currentTarget.dataset.goodsid;
    for (var i = 0; i < this.data.ProductCommentList.length; i++) {
      if (this.data.ProductCommentList[i].ProductID == e.currentTarget.id && this.data.ProductCommentList[i].GoodsID == goodsid) {
        this.data.ProductCommentList[i].CommentContent = e.detail.value;
        break;
      }
    }
  },

  /**
   * 商品评分
   */
  stars: function(e) {
    for (var i = 0; i < this.data.ProductCommentList.length; i++) {
      if (this.data.ProductCommentList[i].ProductID == e.currentTarget.id) {
        this.data.ProductCommentList[i].Score = e.detail.value;
      }
    }
    this.setData({
      star: e.detail.value
    });
  },

  /**
   * 是否匿名
   */
  onCheck: function(e) {
    for (var i = 0; i < this.data.ProductCommentList.length; i++) {
      if (this.data.ProductCommentList[i].ProductID == e.currentTarget.id) {
        if (this.data.ProductCommentList[i].Anonymous == 1)
          this.data.ProductCommentList[i].Anonymous = 0;
        else
          this.data.ProductCommentList[i].Anonymous = 1;
      }
    }
  },
  //上传文件
  upload_file: function(url, filePath, name, success, fail) {
    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: name,
      formData: {
        'customerid': globalData.custID,
        'userid': wx.getStorageSync('UserInfo').UserID,
        'imageType': 0,
        'imageSize': 0,
        'isWeixin': 0
      }, // HTTP 请求中其他额外的参数
      header: {
        
        'content-type': 'multipart/form-data'
      }, // 设置请求的 header
      success: function(res) {
        if (res.statusCode == 200 && !res.data.result_code) {
          typeof success == "function" && success(res.data);
        } else {
          typeof fail == "function" && fail(res);
        }
      },
      fail: function(res) {
        console.log(res);
        typeof fail == "function" && fail(res);
      }
    })
  },

  /**
   * 上传图片
   */
  onUploadPics: function(e) {
    var productId = e.currentTarget.id;
    var goodsId = e.currentTarget.dataset.goodsid;
    var that = this;
    var list = that.data.ProductCommentList;
    var detaillist = that.data.GetOrderDetails;
    wx.chooseImage({
      count: 3, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        for (var i = 0; i < detaillist.length; i++) {
          if (detaillist[i].ProductId == productId && detaillist[i].GoodsID == goodsId) {
            if (detaillist[i].PictureList.length >= 3) {
              wx.showToast({
                title: '最多上传3张图片',
                duration: 2000
              })
              return false;
            }
            break;
          }
        }

        for (var i = 0; i < res.tempFilePaths.length; i++) {
          that.upload_file(globalData.upFileUrl + 'Baidu/AliyunUpload', res.tempFilePaths[i], 'photo',
            function(res) {
              //调用上传文件成功
              //console.log(res);
              var resData = JSON.parse(res)
              // arr.push(resData.url);
              for (var i = 0; i < detaillist.length; i++) {
                if (detaillist[i].ProductId == productId && detaillist[i].GoodsID == goodsId) {
                  var arr = [];
                  if (detaillist[i].PictureList.length > 0) {
                    arr = detaillist[i].PictureList;
                  }
                  arr.push(resData.url);
                  detaillist[i].PictureList = arr;
                  break;
                }
              }
              that.setData({
                ProductCommentList: list,
                GetOrderDetails: detaillist
              })
            });
        }
      }
    })
  },
  /**
   * 删除图片
   */
  onDelPic: function(e) {
    var productId = e.currentTarget.id;
    var goodsId = e.currentTarget.dataset.goodsid;
    var detaillist = this.data.GetOrderDetails;
    var index = e.currentTarget.dataset.index;

    for (var i = 0; i < detaillist.length; i++) {
      if (detaillist[i].ProductId == productId && detaillist[i].GoodsID == goodsId) {
        for (var j = 0; j < detaillist[i].PictureList.length; j++) {
          if (j == index) {
            detaillist[i].PictureList.splice(j, 1);
            break;
          }
        }
        break;
      }
    }
    this.setData({
      GetOrderDetails: detaillist
    })
  },

  /**
   * 提交评价
   */
  onSubmitComment: function(e) {
    var that = this;
    var url = globalData.apiurl + '/mobile/api/Product/AddProductComment';
    var list = that.data.ProductCommentList;
    var detaillist = that.data.GetOrderDetails;

    wx.showModal({
      title: '提交评价',
      content: '确定提交评价吗？',
      success: function(res) {
        if (res.confirm) {
          for (var i = 0; i < list.length; i++) {
            if (list[i].CommentContent == '') {
              wx.showToast({
                title: '请填写评价内容',
                duration: 2000
              })
              return false;
            }
            list[i].UnionStoreID = that.data.shopID;
            //图片
            for (var j = 0; j < detaillist.length; j++) {
              if (detaillist[j].ProductId == list[i].ProductID && detaillist[i].GoodsID == list[i].GoodsID) {
                list[i].Picture = detaillist[i].PictureList.join(',');
                break;
              }
            }
          }

          wx.request({
            url: url,
            data: JSON.stringify(list),
            method: 'POST',
            header: {
              'content-type': 'application/json',
              'X_ManuName': globalData.manuName
            },
            success: function(res) {
              if (res.data.code == 1200) {
                wx.showToast({
                  title: '提交评价成功',
                  duration: 2000
                })
                wx.switchTab({
                  url: '/pages/myorders/myorders',
                })
              } else {
                wx.showModal({
                  title: res.data.msg,
                  showCancel: false,
                  confirmText: "确定"
                })
              }
            },
            fail: function() {
              wx.showToast({
                title: '提交评价失败',
                duration: 2000
              })
            },
            complete: function() {
              //complete
            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    var that = this;
    that.setData({
      shopID: options.shopID
    });
    var custId = globalData.custID;
    this.setData({
      OrderId: options.OrderID
    })
    var url = globalData.apiurl + '/order/api/OrderInfo/GetOrderByOrderId';

    wx.request({
      url: url,
      data: {
        "custId": custId,
        "orderId": options.OrderID,
        "unionShopID": that.data.shopID
      },
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'X_ManuName': globalData.manuName

      },
      success: function(res) {
        var OrderInfo = res.data.content;
        wx.hideLoading();

        var arr = [];
        var OrderDetails = OrderInfo.GetOrderDetails;
        for (var i = 0; i < OrderDetails.length; i++) {
          OrderDetails[i].PictureList = [];

          var obj = new Object();
          obj.ProductID = OrderDetails[i].ProductId;
          obj.CommentContent = ''; //
          obj.Status = 0;
          obj.CommentUser = wx.getStorageSync('UserInfo').UserID;
          obj.Score = 5; //
          obj.Picture = '';
          obj.CustId = globalData.custID;
          obj.Anonymous = 1; //
          obj.OrderNo = that.data.OrderId;
          obj.GoodsID = OrderDetails[i].GoodsID;
          obj.UnionStoreID = OrderDetails[i].UnionStoreID;
          arr.push(obj);
        }

        that.setData({
          ProductCommentList: arr,
          GetOrderDetails: OrderDetails
        })
      },
      fail: function() {
        wx.hideLoading();
        wx.showToast({
          title: '获取订单详情失败',
          duration: 2000
        })
      },
      complete: function() {
        //complete
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})